package com.ihighest.app.infox.adapter;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ihighest.app.common.api.Api;
import com.ihighest.app.common.api.ApiCallback;
import com.ihighest.app.common.api.ApiResult;
import com.ihighest.app.common.kit.AppKit;
import com.ihighest.app.infox.R;

public class HistoryListviewAdapter extends BaseAdapter {

	private JSONArray jsonArray;
	Context context;
	private final LayoutInflater inflater;
	String rid;

	public HistoryListviewAdapter(JSONArray jsonarray, Context context, String rid) {
		super();
		this.jsonArray = jsonarray;
		this.context = context;
		inflater = LayoutInflater.from(context);
		this.rid = rid;
	}

	@Override
	public int getCount() {

		if (jsonArray == null) {
			return 0;
		}
		return jsonArray.length();
	}

	@Override
	public Object getItem(int arg0) {
		try {
			return jsonArray.getJSONObject(arg0);
		} catch (JSONException e) {
			e.printStackTrace();
			return null;
		}
	}

	@Override
	public long getItemId(int arg0) {
		return arg0;
	}

	@Override
	public int getItemViewType(int position) {
		// TODO Auto-generated method stub
		try {
			System.out.println(jsonArray.getJSONObject(position).getString("fromUserId")+"and"+rid);
			
			if (jsonArray.getJSONObject(position).getString("fromUserId").equals(rid)) {
								
				return 0;
			} else {
				return 1;

			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return 1;
		}
	}

	@Override
	public int getViewTypeCount() {
		// TODO Auto-generated method stub
		return 2;
	}

	@Override
	public View getView(int arg0, View convertView, ViewGroup arg2) {
		// TODO Auto-generated method stub

		ViewHolder holder;
		if (convertView == null) {
			holder = new ViewHolder();
			if(getItemViewType(arg0)==0){
			convertView = inflater.inflate(R.layout.infox_history_listviewitem, null);
			}else{
			convertView = inflater.inflate(R.layout.infox_history_listviewitem_right, null);
			}
			holder.item_icon = (ImageView) convertView.findViewById(R.id.id_icon);
		//	holder.item_from = (TextView) convertView.findViewById(R.id.id_from);
			// holder.item_to = (TextView) convertView.findViewById(R.id.id_to);
		//	holder.item_time = (TextView) convertView.findViewById(R.id.id_time);
			holder.item_content = (TextView) convertView.findViewById(R.id.id_content);

			holder.item_image = (ImageView) convertView.findViewById(R.id.id_image);
			holder.item_voice = (ImageView) convertView.findViewById(R.id.id_voice);
			holder.item_layout=(LinearLayout) convertView.findViewById(R.id.id_textlayout);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		try {

			String fromUserId = jsonArray.getJSONObject(arg0).getString("fromUserId");
			String toUserId = jsonArray.getJSONObject(arg0).getString("toUserId");
			getname(fromUserId,  holder.item_icon);
			// getname(toUserId, holder.item_to);

		//	holder.item_time.setText(AppKit.timeToBeforeStr(jsonArray.getJSONObject(arg0).getLong("timestamp")));

			String objectName = jsonArray.getJSONObject(arg0).getString("objectName");
			String content = jsonArray.getJSONObject(arg0).getString("content");
			JSONObject obj = new JSONObject(content);
			if (objectName != null && objectName.equals("RC:TxtMsg")) {
				// 文字内容
				holder.item_layout.setVisibility(View.VISIBLE);
				holder.item_content.setVisibility(View.VISIBLE);
				holder.item_image.setVisibility(View.GONE);
				holder.item_voice.setVisibility(View.GONE);
				holder.item_content.setText(obj.getString("content"));

			} else if (objectName != null && objectName.equals("RC:ImgMsg")) {
				// 图片内容
				holder.item_layout.setVisibility(View.VISIBLE);
				holder.item_content.setVisibility(View.GONE);
				holder.item_image.setVisibility(View.VISIBLE);
				holder.item_voice.setVisibility(View.GONE);
				String url = obj.getString("imageUri");
				holder.item_image.setTag(url);
				// ImageLoader.getInstance().displayImage(url,
				// holder.item_image);
				AppKit.SetNormalImg(url, holder.item_image);
				holder.item_image.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						String url = (String) arg0.getTag();
						if (!TextUtils.isEmpty(url)) {
							AppKit.showBigImageView(context, url);
						}
					}
				});

			} else if (objectName != null && objectName.equals("RC:VcMsg")) {
				// 声音内容
				holder.item_layout.setVisibility(View.GONE);
				holder.item_content.setVisibility(View.GONE);
				holder.item_image.setVisibility(View.GONE);
				holder.item_voice.setVisibility(View.VISIBLE);

				String base64 = obj.getString("content");

				byte[] bytes = Base64.decode(base64, Base64.DEFAULT);
				final String voiceurl = AppKit.getFileFromBytes(bytes).getAbsolutePath();

				holder.item_voice.setTag(true);
				holder.item_voice.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(final View arg0) {
						if ((Boolean) arg0.getTag()) {
							arg0.setTag(false);
							Uri uri = Uri.parse(voiceurl);
							MediaPlayer player = MediaPlayer.create(context, uri);
							player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
								@Override
								public void onCompletion(MediaPlayer p) {
									p.release();
									arg0.setTag(true);
								}
							});
							player.start();    
						}   
					}
				});

			}

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		      
		return convertView;
	}

	private void getname(String rid,  final ImageView imageview) {
		// TODO Auto-generated method stub
		Api.data("member/info/r_" + rid + ".json", new ApiCallback(context, true) {

			@Override
			public void handleSuccess(ApiResult result) {
				// TODO Auto-generated method stub

				try {
					//textview.setText(result.getData().getString("title"));
					String url = result.getData().getString("head");
					AppKit.SetUserImg(url, imageview);

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

			@Override
			public void handleFailure(Exception e, String msg) {
				// TODO Auto-generated method stub

			}
		}, context);

	}

	/**
	 * 替换当前数据源数据
	 * 
	 * @param moreArry
	 * 
	 * @author lkx Created at 2015-10-20 下午8:49:23
	 */
	public void setData(JSONArray jsonArray) {

		this.jsonArray = jsonArray;
		notifyDataSetChanged();
	}

	/**
	 * 向已有数据源中追加数据
	 * 
	 * @param jsonArray
	 * 
	 * @author lkx Created at 2015-10-20 下午8:49:00
	 */
	public void appendData(JSONArray jsonArra) {

		try {
			jsonArray = AppKit.joinJSONArray(jsonArray, jsonArra);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		notifyDataSetChanged();
	}

	class ViewHolder {

		TextView item_from;
		TextView item_to;
		TextView item_time;
		TextView item_content;
		ImageView item_image;
		ImageView item_voice;
		ImageView item_icon;
		LinearLayout item_layout;

	}

}
